/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ClienteInternalFrame.java
 *
 * Created on 25/07/2009, 00:39:14
 */
package br.di0.nyx.cadastro;

import br.di0.sql.consulta.ConsultaPersonDialog;
import br.di0.sql.insert.InsertPerson;
import br.di0.uteis.MetodosUteis;
import br.di0.uteis.MyOwnFocusTraversalPolicy;
import java.awt.Component;
import java.text.ParseException;
import java.util.Vector;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import org.brazilutils.br.cpfcnpj.CpfCnpj;
import strategy.IDocument;
import strategy.concretas.DocNovo;
import strategy.concretas.DocNumeros;

/**
 * @since 2009.08.17
 * @author di0
 */
public class CadastroInternalFrame extends javax.swing.JInternalFrame implements CadastroFrame {

    /** Creates new form ClienteInternalFrame */
    public CadastroInternalFrame(String titulo, int tipo) {
        initComponents();
        this.setTitle(titulo);
        setTipoPerson(tipo);
        if (tipo == FORNECEDOR) {
            habilitarCPF(false);
        } else if (tipo == CLIENTE) {
            habilitarCPF(true);
        }
        codTextField.requestFocusInWindow();
        focusCicle();
        utils.setEnterHowNextTraversalKey(contentsPanel);

        limitarCampos();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        cgcButtonGroup = new javax.swing.ButtonGroup();
        contentsPanel = new javax.swing.JPanel();
        enderecoTextField = new javax.swing.JTextField();
        cepTextField = new javax.swing.JTextField();
        cidadeTextField = new javax.swing.JTextField();
        ufComboBox = new javax.swing.JComboBox(br.di0.uteis.EstadosBrasileiros.ABREVIATURAS);
        codLabel = new javax.swing.JLabel();
        nomeLabel = new javax.swing.JLabel();
        buscaCodButton = new javax.swing.JButton();
        novoCheckBox = new javax.swing.JCheckBox();
        enderecoLabel = new javax.swing.JLabel();
        cepLabel = new javax.swing.JLabel();
        cidadeLabel = new javax.swing.JLabel();
        ufLabel = new javax.swing.JLabel();
        cpfCnpjPanel = new javax.swing.JPanel();
        cpfRadioButton = new javax.swing.JRadioButton();
        cnpjRadioButton = new javax.swing.JRadioButton();
        cpfCnpjTextField = new javax.swing.JTextField();
        nomeTextField = new javax.swing.JTextField();
        telefoneTextField = new javax.swing.JTextField();
        telefoneLabel = new javax.swing.JLabel();
        telefoneTextField2 = new javax.swing.JTextField();
        ieLabel = new javax.swing.JLabel();
        ieTextField = new javax.swing.JTextField();
        codTextField = new javax.swing.JTextField();
        cadastroTextField = new javax.swing.JTextField();
        cadastroLabel = new javax.swing.JLabel();
        comandosPanel = new javax.swing.JPanel();
        salvarButton = new javax.swing.JButton();
        cancelarButton = new javax.swing.JButton();

        setClosable(true);
        setIconifiable(true);
        try {
            setSelected(true);
        } catch (java.beans.PropertyVetoException e1) {
            e1.printStackTrace();
        }
        setVisible(true);

        contentsPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Cadastro"));
        contentsPanel.setFocusCycleRoot(true);

        cepTextField.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                cepTextFieldFocusLost(evt);
            }
        });

        ufComboBox.setMaximumRowCount(6);

        codLabel.setText("Código");

        nomeLabel.setText("Nome");

        buscaCodButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/di0/icones/lupa16x16.png"))); // NOI18N
        buscaCodButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buscaCodButtonActionPerformed(evt);
            }
        });

        novoCheckBox.setMnemonic('N');
        novoCheckBox.setText("Novo");
        novoCheckBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                novoCheckBoxActionPerformed(evt);
            }
        });

        enderecoLabel.setText("Endereço");

        cepLabel.setText("CEP");

        cidadeLabel.setText("Cidade");

        ufLabel.setText("UF");

        cpfCnpjPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(""));

        cpfRadioButton.setMnemonic('F');
        cpfRadioButton.setSelected(true);
        cpfRadioButton.setText("CPF");
        cpfRadioButton.setFocusable(false);
        cgcButtonGroup.add(cpfRadioButton);
        cpfRadioButton.setEnabled(false);
        cpfRadioButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cpfRadioButtonActionPerformed(evt);
            }
        });

        cnpjRadioButton.setMnemonic('P');
        cnpjRadioButton.setText("CNPJ");
        cnpjRadioButton.setFocusable(false);
        cgcButtonGroup.add(cnpjRadioButton);
        cnpjRadioButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cnpjRadioButtonActionPerformed(evt);
            }
        });

        cpfCnpjTextField.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                cpfCnpjTextFieldFocusLost(evt);
            }
        });

        javax.swing.GroupLayout cpfCnpjPanelLayout = new javax.swing.GroupLayout(cpfCnpjPanel);
        cpfCnpjPanel.setLayout(cpfCnpjPanelLayout);
        cpfCnpjPanelLayout.setHorizontalGroup(
            cpfCnpjPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(cpfCnpjPanelLayout.createSequentialGroup()
                .addComponent(cpfRadioButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(cnpjRadioButton))
            .addComponent(cpfCnpjTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE)
        );
        cpfCnpjPanelLayout.setVerticalGroup(
            cpfCnpjPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(cpfCnpjPanelLayout.createSequentialGroup()
                .addGroup(cpfCnpjPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cpfRadioButton)
                    .addComponent(cnpjRadioButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 8, Short.MAX_VALUE)
                .addComponent(cpfCnpjTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        telefoneTextField.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                telefoneTextFieldFocusLost(evt);
            }
        });

        telefoneLabel.setText("Telefone");

        telefoneTextField2.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                telefoneTextField2FocusLost(evt);
            }
        });

        ieLabel.setText("I.E.");

        ieTextField.setText("ISENTO");
        ieTextField.setEnabled(false);

        codTextField.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                codTextFieldFocusLost(evt);
            }
        });

        cadastroTextField.setEditable(false);
        cadastroTextField.setFont(new java.awt.Font("DejaVu Sans", 1, 13)); // NOI18N
        cadastroTextField.setFocusable(false);

        cadastroLabel.setText("Data Cadastro");

        javax.swing.GroupLayout contentsPanelLayout = new javax.swing.GroupLayout(contentsPanel);
        contentsPanel.setLayout(contentsPanelLayout);
        contentsPanelLayout.setHorizontalGroup(
            contentsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(contentsPanelLayout.createSequentialGroup()
                .addGroup(contentsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(contentsPanelLayout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(contentsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(contentsPanelLayout.createSequentialGroup()
                                .addGroup(contentsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(codLabel)
                                    .addComponent(nomeLabel)
                                    .addComponent(enderecoLabel)
                                    .addComponent(cidadeLabel))
                                .addGap(12, 12, 12)
                                .addGroup(contentsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(contentsPanelLayout.createSequentialGroup()
                                        .addComponent(codTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(buscaCodButton)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(novoCheckBox))
                                    .addGroup(contentsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                        .addComponent(nomeTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 255, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addComponent(enderecoTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 255, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addComponent(cidadeTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 255, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGroup(contentsPanelLayout.createSequentialGroup()
                                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                            .addComponent(telefoneTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)
                                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                            .addComponent(telefoneTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                            .addComponent(telefoneLabel))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, contentsPanelLayout.createSequentialGroup()
                        .addContainerGap(246, Short.MAX_VALUE)
                        .addComponent(cadastroLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
                .addGroup(contentsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(ieLabel, javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(cpfCnpjPanel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, contentsPanelLayout.createSequentialGroup()
                        .addGroup(contentsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(cepLabel)
                            .addComponent(ufLabel))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(contentsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(ufComboBox, 0, 115, Short.MAX_VALUE)
                            .addComponent(cadastroTextField, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 115, Short.MAX_VALUE)
                            .addComponent(ieTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 115, Short.MAX_VALUE)
                            .addComponent(cepTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 115, Short.MAX_VALUE))))
                .addGap(51, 51, 51))
        );
        contentsPanelLayout.setVerticalGroup(
            contentsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(contentsPanelLayout.createSequentialGroup()
                .addGroup(contentsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(contentsPanelLayout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(contentsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(codLabel)
                            .addComponent(buscaCodButton, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(novoCheckBox)
                            .addComponent(codTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(contentsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(nomeLabel)
                            .addComponent(nomeTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addComponent(cpfCnpjPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(contentsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(enderecoLabel)
                    .addComponent(enderecoTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(cepLabel)
                    .addComponent(cepTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(10, 10, 10)
                .addGroup(contentsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cidadeTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(cidadeLabel)
                    .addComponent(ufLabel)
                    .addComponent(ufComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(contentsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(telefoneLabel)
                    .addComponent(telefoneTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(ieLabel)
                    .addComponent(ieTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(telefoneTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(contentsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cadastroTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(cadastroLabel))
                .addContainerGap())
        );

        getContentPane().add(contentsPanel, java.awt.BorderLayout.CENTER);

        comandosPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(""));
        comandosPanel.setLayout(new java.awt.GridLayout(1, 0));

        salvarButton.setMnemonic('S');
        salvarButton.setText("Salvar");
        salvarButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                salvarButtonActionPerformed(evt);
            }
        });
        comandosPanel.add(salvarButton);

        cancelarButton.setMnemonic('C');
        cancelarButton.setText("Cancelar");
        cancelarButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelarButtonActionPerformed(evt);
            }
        });
        comandosPanel.add(cancelarButton);

        getContentPane().add(comandosPanel, java.awt.BorderLayout.PAGE_END);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void novoCheckBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_novoCheckBoxActionPerformed
        ativaCodigo(codTextField, !novoCheckBox.isSelected());
        limparTela();
        focusCicle();
    }//GEN-LAST:event_novoCheckBoxActionPerformed

    private void cpfCnpjTextFieldFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_cpfCnpjTextFieldFocusLost
        Component comp = evt.getOppositeComponent();
        if (comp != null) {
            if (comp.getName() == null) {
                String mascara;
                String aux = new String(cpfCnpjTextField.getText());
                aux = aux.replace(".", "");
                aux = aux.replace("-", "");
                aux = aux.replace("/", "");
                CpfCnpj cpfCnpj = new CpfCnpj();
                cpfCnpj.setCpfCnpj(aux);

                if (!aux.equals("")) {
                    if (cpfRadioButton.isSelected()) {
                        System.out.println("CPF");
                        mascara = new String(CpfCnpj.CPF_MASK);
                        if (!cpfCnpj.isCpf() || !cpfCnpj.isValid()) {
                            JOptionPane.showMessageDialog(null, "CPF incorreto",
                                    "ERRO", JOptionPane.ERROR_MESSAGE);
                            cpfCnpjTextField.requestFocus();
                        }
                    } else {
                        mascara = new String(CpfCnpj.CNPJ_MASK);
                        if ((!cpfCnpj.isCnpj() || !cpfCnpj.isValid())) {
                            JOptionPane.showMessageDialog(null, "CNPJ incorreto",
                                    "ERRO", JOptionPane.ERROR_MESSAGE);
                            cpfCnpjTextField.requestFocus();
                        }
                    }

                    try {
                        cpfCnpjTextField.setText(utils.formatarString(aux, mascara)); //altera formatação
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                } else {
                    cpfCnpjTextField.setText("");
                }
            }
        }

}//GEN-LAST:event_cpfCnpjTextFieldFocusLost

    private void cnpjRadioButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cnpjRadioButtonActionPerformed
        cpfRadioButton.setEnabled(true);
        cnpjRadioButton.setEnabled(false);
        ieTextField.setEnabled(true);
        ieTextField.setText("");
        cpfCnpjTextField.setText("");
        limitarCampoCPF();
        focusCicle();
    }//GEN-LAST:event_cnpjRadioButtonActionPerformed

    private void cpfRadioButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cpfRadioButtonActionPerformed
        cpfRadioButton.setEnabled(false);
        cnpjRadioButton.setEnabled(true);
        ieTextField.setEnabled(false);
        ieTextField.setText("ISENTO");
        cpfCnpjTextField.setText("");
        limitarCampoCPF();
        focusCicle();
    }//GEN-LAST:event_cpfRadioButtonActionPerformed

    private void cepTextFieldFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_cepTextFieldFocusLost
        Component comp = evt.getOppositeComponent();
        if (comp != null) {
            if (comp.getName() == null) {
                formatarCEP(cepTextField);
            }
        }
    }//GEN-LAST:event_cepTextFieldFocusLost

    private void salvarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_salvarButtonActionPerformed
        String[] person = new String[12];

        person[0] = codTextField.getText();
        person[1] = nomeTextField.getText();
        if (cpfRadioButton.isSelected()) {
            person[2] = "1";
        } else {
            person[2] = "2";
        }
        person[3] = cpfCnpjTextField.getText();
        person[4] = ieTextField.getText();
        if (person[4].equals("")) {
            person[4] = "ISENTO";
        }
        person[5] = enderecoTextField.getText();
        person[6] = cepTextField.getText();
        person[7] = cidadeTextField.getText();
        person[8] = Integer.toString(ufComboBox.getSelectedIndex());
        person[9] = telefoneTextField.getText();
        person[10] = telefoneTextField2.getText();
        person[11] = telefoneTextField2.getText();

        if (novoCheckBox.isSelected()) {
            inserir(person);
        } else {
            atualizar(person);
        }
}//GEN-LAST:event_salvarButtonActionPerformed

    private void cancelarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelarButtonActionPerformed
        novoCheckBox.setSelected(false);
        codTextField.setEnabled(true);
        buscaCodButton.setEnabled(true);
        codTextField.requestFocus();
        limparTela();
        limitarCampoCPF();
        focusCicle();
    }//GEN-LAST:event_cancelarButtonActionPerformed

    private void telefoneTextFieldFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_telefoneTextFieldFocusLost
        Component comp = evt.getOppositeComponent();
        if (comp != null) {
            if (comp.getName() == null) {
                formatarTelefone(telefoneTextField);
            }
        }
    }//GEN-LAST:event_telefoneTextFieldFocusLost

    private void telefoneTextField2FocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_telefoneTextField2FocusLost
        Component comp = evt.getOppositeComponent();
        if (comp != null) {
            if (comp.getName() == null) {
                formatarTelefone(telefoneTextField2);
            }
        }
    }//GEN-LAST:event_telefoneTextField2FocusLost

    private void buscaCodButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buscaCodButtonActionPerformed
        ConsultaPersonDialog person = new ConsultaPersonDialog(null, true, this);
        System.out.println("Tipo dialog: "+getTipoPerson());
        if (getTipoPerson() == CadastroInternalFrame.CLIENTE) {
            person.setTitle("Clientes");
            System.out.println("Alterou titulo cliente");
        } else if (getTipoPerson() == CadastroInternalFrame.FORNECEDOR) {
            person.setTitle("Fornecedores");
            System.out.println("Alterou titulo fornecedor");
        }
        person.setVisible(true);
    }//GEN-LAST:event_buscaCodButtonActionPerformed

    private void codTextFieldFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_codTextFieldFocusLost
        Component comp = evt.getOppositeComponent();
        if (comp != null) {
            if (comp.getName() == null) {
                carregarPerson();
            }
        }
    }//GEN-LAST:event_codTextFieldFocusLost

    public void carregarPerson() {
        String per = null;
        if (tipoPerson == CLIENTE) {
            per = "Cliente";
        } else {
            per = "Fornecedor";
        }

        String codPerson = codTextField.getText();
        InsertPerson db = new InsertPerson(tipoPerson);

        if (!codPerson.equals("")) {
            String person[] = db.localizar(codPerson);
            if (person != null) {
                codTextField.setEnabled(false);

                nomeTextField.setText(person[0]);
                if (person[1].equals("1")) {
                    cpfRadioButton.setSelected(true);
                    cpfRadioButtonActionPerformed(null);
                } else {
                    cnpjRadioButton.setSelected(true);
                    cnpjRadioButtonActionPerformed(null);
                }
                cpfCnpjTextField.setText(person[2]);
                ieTextField.setText(person[3]);
                enderecoTextField.setText(person[4]);
                cepTextField.setText(person[5]);
                cidadeTextField.setText(person[6]);
                ufComboBox.setSelectedIndex(Integer.parseInt(person[7]));
                telefoneTextField.setText(person[8]);
                telefoneTextField2.setText(person[9]);

                String dataFormat = MetodosUteis.timeStampToString(person[10]);
                cadastroTextField.setText(dataFormat);
            } else {
                JOptionPane.showMessageDialog(null, "Código não encontrado",
                        "Cadastro de " + per, JOptionPane.ERROR_MESSAGE);
                codTextField.setText("");
                codTextField.requestFocus();
            }
        }
    }

    public void setCodText(String cod) {
        codTextField.setText(cod);
        carregarPerson();
    }

    private void inserir(String[] person) {
        String per = null;
        if (tipoPerson == CLIENTE) {
            per = "Cliente";
        } else {
            per = "Fornecedor";
        }

        if (person[1].equals("")) {
            JOptionPane.showMessageDialog(null, "Digite um nome para o " + per + ".",
                    "Cadastro de " + per, JOptionPane.WARNING_MESSAGE);
            nomeTextField.requestFocus();
        } else if (person[2].equals("")) {
            JOptionPane.showMessageDialog(null, "Selecione CPF ou CNPJ.",
                    "Cadastro de " + per, JOptionPane.WARNING_MESSAGE);
            cpfRadioButton.requestFocus();
        } else if (person[3].equals("")) {
            String cgc = null;
            if (cpfRadioButton.isSelected()) {
                cgc = "CPF";
            } else {
                cgc = "CNPJ";
            }
            JOptionPane.showMessageDialog(null, cgc + " não digitado.",
                    "Cadastro de " + per, JOptionPane.WARNING_MESSAGE);
            cpfCnpjTextField.requestFocus();
        } else if (person[5].equals("")) {
            JOptionPane.showMessageDialog(null, "Endereço não digitado.",
                    "Cadastro de " + per, JOptionPane.WARNING_MESSAGE);
            enderecoTextField.requestFocus();
        } else if (person[7].equals("")) {
            JOptionPane.showMessageDialog(null, "Cidade não digitada.",
                    "Cadastro de " + per, JOptionPane.WARNING_MESSAGE);
            cidadeTextField.requestFocus();
        } else if (person[8].equals("")) {
            JOptionPane.showMessageDialog(null, "Estado não selecionado.",
                    "Cadastro de " + per, JOptionPane.WARNING_MESSAGE);
            ufComboBox.requestFocus();
        } else {
            InsertPerson db = new InsertPerson(tipoPerson);
            int result = db.inserir(person); // inserir no banco
            if (result == InsertPerson.ERROR_USER_NOT_FOUND) {
                JOptionPane.showMessageDialog(null, "Usuário não encontrado.",
                        "Cadastro de " + per, JOptionPane.ERROR_MESSAGE);
            } else if (result == 1) {
                JOptionPane.showMessageDialog(null, per + " [" + person[1] +
                        "] cadastrado com sucesso.",
                        "Cadastro de " + per, JOptionPane.INFORMATION_MESSAGE);
                limparTela();
            } else {
                JOptionPane.showMessageDialog(null, "Não foi possivel cadastrar o " + per + ".",
                        "Cadastro de " + per, JOptionPane.INFORMATION_MESSAGE);
                nomeTextField.requestFocus();
            }
        }

    }

    private void atualizar(String[] person) {
        String per = null;
        if (tipoPerson == CLIENTE) {
            per = "Cliente";
        } else {
            per = "Fornecedor";
        }

        if (person[0].equals("")) {
            JOptionPane.showMessageDialog(null, "Digite um código válido para o " + per + ".",
                    "Cadastro de " + per, JOptionPane.WARNING_MESSAGE);
            nomeTextField.requestFocus();
        } else if (person[1].equals("")) {
            JOptionPane.showMessageDialog(null, "Digite um nome para o " + per + ".",
                    "Cadastro de " + per, JOptionPane.WARNING_MESSAGE);
            nomeTextField.requestFocus();
        } else if (person[2].equals("")) {
            JOptionPane.showMessageDialog(null, "Selecione CPF ou CNPJ.",
                    "Cadastro de " + per, JOptionPane.WARNING_MESSAGE);
            cpfRadioButton.requestFocus();
        } else if (person[3].equals("")) {
            String cgc = null;
            if (cpfRadioButton.isSelected()) {
                cgc = "CPF";
            } else {
                cgc = "CNPJ";
            }
            JOptionPane.showMessageDialog(null, cgc + " não digitado.",
                    "Cadastro de " + per, JOptionPane.WARNING_MESSAGE);
            cpfCnpjTextField.requestFocus();
        } else if (person[5].equals("")) {
            JOptionPane.showMessageDialog(null, "Endereço não digitado.",
                    "Cadastro de " + per, JOptionPane.WARNING_MESSAGE);
            enderecoTextField.requestFocus();
        } else if (person[7].equals("")) {
            JOptionPane.showMessageDialog(null, "Cidade não digitada.",
                    "Cadastro de " + per, JOptionPane.WARNING_MESSAGE);
            cidadeTextField.requestFocus();
        } else if (person[8].equals("")) {
            JOptionPane.showMessageDialog(null, "Estado não selecionado.",
                    "Cadastro de " + per, JOptionPane.WARNING_MESSAGE);
            ufComboBox.requestFocus();
        } else {
            InsertPerson db = new InsertPerson(tipoPerson);
            int result = db.atualizar(person); // inserir no banco
            if (result == InsertPerson.ERROR_USER_NOT_FOUND) {
                JOptionPane.showMessageDialog(null, "Usuário não encontrado.",
                        "Cadastro de " + per, JOptionPane.ERROR_MESSAGE);
            } else if (result == 1) {
                JOptionPane.showMessageDialog(null, per + " [" + person[1] +
                        "] alterado com sucesso.",
                        "Cadastro de " + per, JOptionPane.INFORMATION_MESSAGE);

                limparTela();
            } else if (result == InsertPerson.ERROR_ID_NOT_FOUND) {
                JOptionPane.showMessageDialog(null, "Código não encontrado.",
                        "Cadastro de " + per, JOptionPane.ERROR_MESSAGE);
                JOptionPane.showMessageDialog(null, "Não foi possivel alterar o " + per + ".",
                        "Cadastro de " + per, JOptionPane.ERROR_MESSAGE);
                nomeTextField.requestFocus();
            }
        }
    }

    /**
     * Aplica Expressões Regulares em JTextFields da janela
     */
    public void limitarCampos() {
        //código
        doc = new DocNumeros(5);
        codTextField.setDocument(doc.getDocumentoPlano());

        //nome
        /*doc = new DocNovo("", 50);
        nomeTextField.setDocument(doc.getDocumentoPlano());*/

        //CEP
        doc = new DocNovo("[0-9|\\-|\\.]*");
        cepTextField.setDocument(doc.getDocumentoPlano());

        //CPF
        limitarCampoCPF();

        //TELEFONE
        doc = new DocNovo("[0-9|\\(|\\)|\\-]*");
        telefoneTextField.setDocument(doc.getDocumentoPlano());
        doc = new DocNovo("[0-9|\\(|\\)|\\-]*");
        telefoneTextField2.setDocument(doc.getDocumentoPlano());
    }

    /**
     * Aplica Expressão Regular no JTextField de CPF e CNPJ
     */
    private void limitarCampoCPF() {
        //CPF
        if (cpfRadioButton.isSelected()) {
            doc = new DocNovo("[\\d|\\.|\\-]+");
            cpfCnpjTextField.setDocument(doc.getDocumentoPlano());
        } else {
            doc = new DocNovo("[\\d|\\.|\\-|\\/]+");
        }

        cpfCnpjTextField.setDocument(doc.getDocumentoPlano());
    }

    /**
     * Habilita ou desabilita o tratamento de CPF. Caso falso, o painel de controle
     * de CPF será alterado para aceitar somente CNPJ.
     * @param status o status a ser definido para o CPF.
     */
    private void habilitarCPF(boolean status) {
        cpfAtivo = status;
        if (!status) {
            cnpjRadioButton.setSelected(true);
            cpfRadioButton.setVisible(false);
            cnpjRadioButton.setVisible(false);
            cpfCnpjPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("CNPJ"));
            ieTextField.setEnabled(true);
            ieTextField.setText("");
        }
    }

    /**
     * Aplica Expressão Regular de CEP no formato ##.###-###. Emite erro se a
     * quantidade de números digitados for diferente de oito.
     * @param cep o JTextField a ser tratado.
     */
    private void formatarCEP(JTextField cep) {
        String aux = new String(cep.getText());
        aux = aux.replace("-", "");
        aux = aux.replace(".", "");

        if (aux.length() == 8) {
            try {
                cep.setText(utils.formatarString(aux, CEP_MASK)); //altera formatação
            } catch (ParseException e) {
                JOptionPane.showMessageDialog(null, "Erro no formato do CEP",
                        "ERRO", JOptionPane.ERROR_MESSAGE);
                cep.requestFocus();
            }
        } else if (aux.length() != 0) {
            JOptionPane.showMessageDialog(null, "Erro no formato do CEP",
                    "ERRO", JOptionPane.ERROR_MESSAGE);
            cep.requestFocus();
        }
    }

    /**
     * Aplica Expressão Regular de Telefone no formato (##)####-####. Emite erro
     * se a quantidade de números digitados for diferente de dez.
     * @param telefone o JTextField a ser tratado.
     */
    private void formatarTelefone(JTextField telefone) {
        String aux = new String(telefone.getText());
        aux = aux.replace("(", "");
        aux = aux.replace(")", "");
        aux = aux.replace("-", "");

        if (aux.length() == 10) {
            try {
                telefone.setText(utils.formatarString(aux, TELEFONE_MASK)); //altera formatação
            } catch (ParseException e) {
                JOptionPane.showMessageDialog(null, "Erro no formato do Telefone",
                        "ERRO", JOptionPane.ERROR_MESSAGE);
                telefone.requestFocus();
            }
        } else if (aux.length() != 0) {
            JOptionPane.showMessageDialog(null, "Erro no formato do Telefone",
                    "ERRO", JOptionPane.ERROR_MESSAGE);
            telefone.requestFocus();
        }
        if (aux.equals("")) {
            telefone.setText("");
        }
    }

    /**
     * Limpa os campos da janela.
     */
    public void limparTela() {
        utils.limparCampos(contentsPanel);
        limitarCampoCPF();
        ufComboBox.setSelectedIndex(0);
        resetRadios();
        if (cpfAtivo) {
            ieTextField.setEnabled(false);
            ieTextField.setText("ISENTO");
        } else {
            ieTextField.setText("");
        }
        if (novoCheckBox.isSelected()) {
            codTextField.setEnabled(false);
            nomeTextField.requestFocus();
        } else {
            codTextField.setEnabled(true);
            codTextField.requestFocus();
        }
    }

    /**
     * Redefine o cpfRadioButton como item selecionado.
     */
    private void resetRadios() {
        if (cpfAtivo) {
            cpfRadioButton.setSelected(true);
            cpfRadioButton.setEnabled(false);
            cnpjRadioButton.setEnabled(true);
        }
    }

    /**
     * Controle do JCheckBox novo.
     * @param codigoField o campo JTextField referente ao código.
     * @param desativar o status
     */
    public void ativaCodigo(JTextField codigoField, boolean desativar) {
        codigoField.setEnabled(desativar);
        if (!codigoField.isEnabled()) {
            codigoField.setText("");
        }
        buscaCodButton.setEnabled(desativar);
    }

    /**
     * Define o ciclo de foco nos itens da janela.
     */
    public void focusCicle() {
        order = new Vector<Component>(14);
        if (!novoCheckBox.isSelected()) {
            order.add(codTextField);
            order.add(buscaCodButton);
        }
        order.add(novoCheckBox);
        order.add(nomeTextField);
        order.add(cpfCnpjTextField);
        order.add(enderecoTextField);
        order.add(cepTextField);
        order.add(cidadeTextField);
        order.add(ufComboBox);
        order.add(telefoneTextField);
        order.add(telefoneTextField2);
        if (ieTextField.isEnabled()) {
            order.add(ieTextField);
        }

        order.add(salvarButton);
        order.add(cancelarButton);

        newPolicy = new MyOwnFocusTraversalPolicy(order);
        this.setFocusTraversalPolicy(newPolicy);
    }

    private IDocument doc;
    private MetodosUteis utils = new MetodosUteis();
    private boolean cpfAtivo;
    public static String TELEFONE_MASK = new String("(##)####-####");
    public static String CEP_MASK = new String("##.###-###");
    public static final int CLIENTE = 1;
    public static final int FORNECEDOR = 2;
    private int tipoPerson;
    private MyOwnFocusTraversalPolicy newPolicy;
    private Vector<Component> order = new Vector<Component>(12);
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton buscaCodButton;
    private javax.swing.JLabel cadastroLabel;
    private javax.swing.JTextField cadastroTextField;
    private javax.swing.JButton cancelarButton;
    private javax.swing.JLabel cepLabel;
    private javax.swing.JTextField cepTextField;
    private javax.swing.ButtonGroup cgcButtonGroup;
    private javax.swing.JLabel cidadeLabel;
    private javax.swing.JTextField cidadeTextField;
    private javax.swing.JRadioButton cnpjRadioButton;
    private javax.swing.JLabel codLabel;
    private javax.swing.JTextField codTextField;
    private javax.swing.JPanel comandosPanel;
    private javax.swing.JPanel contentsPanel;
    private javax.swing.JPanel cpfCnpjPanel;
    private javax.swing.JTextField cpfCnpjTextField;
    private javax.swing.JRadioButton cpfRadioButton;
    private javax.swing.JLabel enderecoLabel;
    private javax.swing.JTextField enderecoTextField;
    private javax.swing.JLabel ieLabel;
    private javax.swing.JTextField ieTextField;
    private javax.swing.JLabel nomeLabel;
    private javax.swing.JTextField nomeTextField;
    private javax.swing.JCheckBox novoCheckBox;
    private javax.swing.JButton salvarButton;
    private javax.swing.JLabel telefoneLabel;
    private javax.swing.JTextField telefoneTextField;
    private javax.swing.JTextField telefoneTextField2;
    private javax.swing.JComboBox ufComboBox;
    private javax.swing.JLabel ufLabel;
    // End of variables declaration//GEN-END:variables

    /**
     * @return the tipoPerson
     */
    public int getTipoPerson() {
        return tipoPerson;
    }

    /**
     * @param tipoPerson the tipoPerson to set
     */
    public void setTipoPerson(int tipoPerson) {
        this.tipoPerson = tipoPerson;
    }
}
